package com.it.service.impl;

import com.it.entity.User;
import com.it.mapper.UserMapper;
import com.it.service.IUserService;
import com.it.service.ex.InsertException;
import com.it.service.ex.UsernameDuplicatedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.UUID;

@Service
//用户模块业务层的实现类
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void reg(User user) {
//        通过user参数来获取传递过来的username
        String username = user.getUsername();
//        调用findByUsername判断用户是否被注册过
      User result=  userMapper.findByUsername(username);
//        判断结果集是否不为null则抛出用户名被占用的异常
        if(result !=null){
            throw new UsernameDuplicatedException("用户名被占用");
        }
        //密码加密处理：md5算法  盐+password+盐
        String oldPassword = user.getPassword();
        //随机生产一个盐
        String salt = UUID.randomUUID().toString().toUpperCase();
        //补全数据盐值的记录
        user.setSalt(salt);
        //将密码和盐作为一个整体加密处理
        String md5Password = getMD5Password(oldPassword, salt);
        //将加密之后的密码重新补全到user对象中
        user.setPassword(md5Password);
        //补全数据：is_delete设置0
        user.setIsDelete(0);
        //补全数据：日志字段
        user.setCreatedUser(user.getUsername());
        user.setModifiedUser(user.getUsername());
        Date date = new Date();
        user.setCreatedTime(date);
        user.setModifiedTime(date);
//        执行注册业务功能的视线(rows==1)
        Integer rows =userMapper.insert(user);
        if (rows !=1){
            throw  new InsertException("用户注册过程中产生了未知的异常");
        }

    }

    @Override
    public User denglu(String username, String Password) {
        return null;
    }
    @Override
    public  void  changePassword(Integer uid,String username,String oldPassword,String newPassword){

    }


    /*定义一个md5算法的加密*/
    private  String getMD5Password(String password,String salt){
        for (int i = 0; i < 3; i++) {
            password= DigestUtils.md5DigestAsHex((salt+password+salt).getBytes()).toUpperCase();

        }
        return password;
    }
}
